var gameInit = function () {
  document.getElementById('gameContainer').style.height = document.body.clientHeight + 'px';
  var width = window.innerWidth;
  var height = window.innerHeight;
  var Ratio = window.devicePixelRatio;

  //获取屏幕的宽和高
  var w = document.documentElement.clientWidth || document.body.clientWidth;
  var h = document.documentElement.clientHeight || document.body.clientHeight;
  var ww = Ratio * w;
  var hh = Ratio * h;
  var game = new Phaser.Game(ww, hh, Phaser.AUTO, 'gameContainer');
  // Phaser.World.prototype.displayObjectUpdateTransform = function() {
  //   if(!game.scale.correct) {
  //     this.x = game.camera.y + game.width;
  //     this.y = -game.camera.x;
  //     this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(90));
  //   } else {
  //     this.x = -game.camera.x;
  //     this.y = -game.camera.y;
  //     this.rotation = 0;
  //   }
   
  //   PIXI.DisplayObject.prototype.updateTransform.call(this);
  // }
  var resize = function () {
    var canvas = document.querySelector("canvas");
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    var windowRatio = windowWidth / windowHeight;
    if (windowWidth < windowHeight) {
      canvas.style.width = windowWidth + "px";
      canvas.style.height = windowHeight + "px";
    } else {
      canvas.style.width = windowHeight + "px";
      canvas.style.height = windowHeight + "px";
    }
  }
  // window.addEventListener("resize", resize, false);
  var states = {

    loading: function () {
      function enterIncorrectOrientation() {
        alert('请将手机纵向摆放');
      }
      function leaveIncorrectOrientation() {
        alert('已经将手机纵向摆放');
      }
      this.init = function () {
        //game.device.desktop判斷是WAP端還是PC端，true為PC端，false為WAP端
        if (!game.device.desktop) {
          //设置游戏背景色
          game.stage.backgroundColor = '#282C34';
          //鼠标指针对象，由于WAP端没有鼠标，因此设置为1（即为null）
          game.input.maxPointers = 1;
          //缩放控制，这里将画布（canvas）拉伸至填满父容器（即#game-container），不保持比例
          game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
          //启用时，显示画布（canvas）将在父容器中水平对齐
          game.scale.pageAlignHorizontally = true;
          //启用时，显示画布（canvas）将在父容器中垂直对齐
          game.scale.pageAlignVertically = true;
          //强制游戏只能以一个方向运行，这里设置游戏仅能在纵向模式运行（true），无法再横向模式运行（false）
          game.scale.forceOrientation(false, true);
          //当forceOrientation设置只能纵向模式运行，把手机横向摆放就会调用enterIncorrectOrientation这个方法
          game.scale.enterIncorrectOrientation.add(enterIncorrectOrientation, this);
          //当forceOrientation设置只能纵向模式运行，把手机横向摆放就会调用enterIncorrectOrientation这个方法，重新将手机纵向摆放就会调用leaveIncorrectOrientation这个方法
          game.scale.leaveIncorrectOrientation.add(leaveIncorrectOrientation, this);
          game.stage.disableVisibilityChange = true;
        } else {
          game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
          game.scale.pageAlignHorizontally = true
          game.scale.pageAlignVertically = true
          //防止浏览器失去焦点后动画暂停，如果考虑到计算机性能可以设置为false
          game.stage.disableVisibilityChange = true;
        }
      }
      this.preload = function () {
        console.log('preload')
        game.load.atlasXML('loadImg', 'assets/image/loading/sprites.png', 'assets/image/loading/sprites.xml');
      }
      this.create = function () {
        console.log('create')
        setTimeout(function () {
          game.state.start('preload')
        }, 2000)
      }

    },
    preload: function () {
      var loadImg;
      var progressText;
      this.init = function () {
        loadImg = game.add.sprite(game.world.centerX - 10, game.world.centerY - 40, 'loadImg');
        loadImg.anchor.set(0.5, 0.5);
        loadImg.animations.add('loadImg_away', [0, 1, 2, 3, 4]);
        loadImg.play('loadImg_away', 10, true);
        progressText = game.add.text(game.world.centerX - 50, game.world.centerY + 70, '0%', {
          fill: '#fff',
          fontSize: '16px'
        });
        progressText.font = '微软雅黑';
      }
      this.preload = function () {
          game.load.atlasXML('bgImg', 'assets/image/bg/bg.png', 'assets/image/bg/bg.xml');
          game.load.atlasXML('runingImg', 'assets/image/runing/sprites.png', 'assets/image/runing/sprites.xml')
          game.load.atlasXML('heImg', 'assets/image/he/sprites.png', 'assets/image/he/sprites.xml')
          game.load.spritesheet('myplane', 'assets/image/myplane.png', 40, 40, 4);
        },
        this.create = function () {
          // TO-DO
          game.stage.backgroundColor = '#aaa';
          setTimeout(function () {
            game.state.start('created');
          }, 1000);
        }
    },
    created: function () {
      var bgImg;
      var touching = false;
      var runingMan;
      this.score = 0;
      this.scoreText = null;
      this.myplane = null;
      this.bounds = null;
      this.create = function () {
        // 开启物理引擎
        var self = this;

        game.world.setBounds(0, 0, game.world.width, game.world.height);
        let boundsbetween = 60;
        game.physics.startSystem(Phaser.Physics.ARCADE);
        bgImg = game.add.sprite(0, 0, 'bgImg');
        bgImg.width = game.world.width;
        bgImg.height = game.world.height;
        // bgImg.anchor.set(0.5, 0.5);
        bgImg.animations.add('bgImg_away', [0, 1, 2, 3]);
        bgImg.play('bgImg_away', 10, true);
        //添加飞机
        this.createPlane();
        this.bounds = new Phaser.Rectangle(boundsbetween, 0, game.width - boundsbetween * 2, game.height);

        // 添加跑人
        this.createRuningMan();
        //创建敌人
        this.creatEnemyGroup();
        var style = {
          font: "bold 32px Arial",
          fill: "#ff0000",
          boundsAlignH: "center",
          boundsAlignV: "middle"
        };
        this.scoreText = game.add.text(game.world.centerX, 20, "Score: " + this.score, style)
      }
      this.createPlane = function () {
        //飞机不动
        this.myplane = game.add.sprite(game.world.centerX, 200, 'myplane');
        //设置中心点
        this.myplane.anchor.set(0.5, 0.5);
        //开启物理模型
        // game.physics.arcade.enable(this.myplane);
        this.myplane.scale.setTo(2, 2);
        this.myplane.animations.add('fly');
        this.myplane.animations.play('fly', 12, true);
        //设置边界
        // this.myplane.body.collideWorldBounds = true;
        // 设置层级
        // this.myplane.level = 2;
        game.add.tween(this.myplane).to({
          y: game.height - 100
        }, 1000, Phaser.Easing.Sinusoidal.InOut, true);
        // this.myplane.inputEnabled = true;
        // this.myplane.input.enableDrag(false);
      }
      this.createRuningMan = function () {
        console.log(game.world);
        runingMan = game.add.sprite(game.world.centerX, game.world.centerY, 'runingImg');
        runingMan.anchor.set(0.5, 0.5);
        runingMan.scale.setTo(0.5, 0.5);
        runingMan.animations.add('runingMan_away', [0, 1, 2]);
        runingMan.play('runingMan_away', 10, true);
        game.add.tween(runingMan.scale).to({
          x: 1,
          y: 1
        }, 1000, Phaser.Easing.Sinusoidal.InOut, true)
        game.add.tween(runingMan).to({
          y: game.world.centerY - 200
        }, 1000, Phaser.Easing.Sinusoidal.InOut, true)
        // 启用物理模型
        game.physics.arcade.enable(runingMan);
        // 设置世界的边界
        runingMan.body.collideWorldBounds = true;
        // 开启事件
        runingMan.inputEnabled = true;
        runingMan.input.enableDrag(false);
        // runingMan.body.bounce.x = 0.2;
        //不允许y移动
        runingMan.input.allowVerticalDrag = false;
        runingMan.input.boundsRect = this.bounds;
        runingMan.level = 3;
      }
      this.creatEnemyGroup = function () {
        // 创建敌人组
        this.enemys = game.add.group();
        // this.enemys.createMultiple(50, 'heImg');
        this.enemys.enableBody = true;
        this.enemys.setAll('checkWorldBounds', true);
        this.enemys.setAll('outOfBoundsKill', true);
        // this.enemys.setAll('body.velocity.y', -400);
        this.count = 0;
        this.EnemysInfo = [{
            name: "glod.png",
            score: 20
          },
          {
            name: "p1.png",
            score: 30
          },
          {
            name: "mu1.png",
            score: -30
          },
          {
            name: "mu2.png",
            score: 40
          },
        ]
        // 添加得分或减分物品，900毫秒执行一次
        game.time.events.loop(700, this.randomCreateEnemys, this);
      }
      this.randomCreateEnemys = function () {
        let randomNum = game.rnd.integerInRange(0, 100);
        if (randomNum > 50) {
          game.time.events.add(350, function () {
            this.generateEnemys(this.EnemysInfo[game.rnd.integerInRange(0, 3)], randomNum);
          }, this);
        }
        this.generateEnemys(this.EnemysInfo[game.rnd.integerInRange(0, 3)], randomNum);
      }
      this.generateEnemys = function (info, randomNum) {
        var enemy = this.enemys.getFirstExists(false);
        let x = randomNum > 40 ? game.world.centerX - game.world.width / 4 : game.world.centerX + game.world.width / 4;
        if (enemy == null) {
          enemy = this.enemys.create(x, game.world.height, 'heImg');
          enemy.anchor.set(0.5);
          // enemy.scale.set(0.5);
          enemy.frameName = info.name
          enemy.score = info.score;
          enemy.body.velocity.y = -800;
        } else {
          let info = this.EnemysInfo[game.rnd.integerInRange(0, 3)];
          enemy.reset(x, game.world.height);
          enemy.frameName = info.name;
          enemy.score = info.score;
          enemy.body.velocity.y = -800;
        }
      }
      this.hitEnemys = function (man, enemy) {
        console.log(enemy.score)
        this.score += enemy.score
        enemy.kill();
      }
      this.update = function () {
        game.debug.body(runingMan)
        game.physics.arcade.overlap(runingMan, this.enemys, this.hitEnemys, null, this);
        this.enemys.forEach(function(enemy){
          if(enemy.y<0){
            enemy.kill();
          }
        })
        this.scoreText.setText("Score: " + this.score);
      }
    },
    play: function () {},
    over: function () {}
  }

  Object.keys(states).map(function (key) {
    game.state.add(key, states[key]);
  });
  game.state.start('loading');
}
window.addEventListener('load', function () {
  setTimeout(() => {
    gameInit();
  }, 300);
}, false);